<?php

namespace App\Http\Controllers\Api;

use App\Constants\MemberTaskConstant;
use App\Constants\MiniProgramConstant;
use App\Http\Requests\Api\ArticleRequest;
use App\Http\Requests\Api\MemberRequest;
use App\Http\Resources\ArticleResource;
use App\Http\Resources\CommentResource;
use App\Http\Resources\MemberResource;
use App\Models\Article;
use App\Models\Member;
use App\Services\SmsService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class MemberController extends Controller
{
    public function me()
    {
        return $this->success('success', new MemberResource(auth('api')->user()->loadCount('topic', 'publisher', 'messages')));
    }

    public function update(MemberRequest $request)
    {
        $member = auth('api')->user();

        $data = $request->only(['sex', 'sign', 'nickname', 'avatar']);
        $member->update($data);

        return $this->success('success', new MemberResource($member));
    }

    public function articleIndex()
    {
        if (!$publisher = auth('api')->user()->publisher) {
            return $this->error('暂无权限');
        }

        $articles = $publisher->articles;

        return $this->success('success', ArticleResource::collection($articles));
    }

    public function articleStore(ArticleRequest $request)
    {
        if (!$publisher = auth('api')->user()->publisher) {
            return $this->error('暂无权限');
        }

        Article::create([
            'publish_id' => $publisher->id,
            'type'       => 1,
            'file_type'  => 1,
            'files'      => $request->images,
            'title'      => $request->title,
            'content'    => $request->content,
            'tag_id'     => $request->tag_id ?: 0,
            'mini_type'  => $this->getMiniType(),
        ]);

        return $this->success('success');
    }

    public function commentIndex(Request $request)
    {
        $validated = $request->validate([
            'status' => 'required|integer|between:0,2',
        ], [
            'status.required' => '状态码必填',
            'status.integer'  => '状态码格式错误',
            'status.between'  => '状态码格式错误',
        ]);
        $where['status'] = $validated['status'];

        $member = auth('api')->user();
        $articleComments = $member->ArticleComments()
            ->select(DB::raw("id,article_id,content,created_at,1 as type"))
            ->with('article.publisher')
            ->where($validated)
            ->paginate(10);

        $articleComments = CommentResource::collection($articleComments);

        $topicComments = $member->TopicComments()
            ->select(DB::raw("id,topic_id,content,created_at,2 as type"))
            ->with('topic.member')
            ->where($where)
            ->paginate(10);

        $topicComments = CommentResource::collection($topicComments);

        $list = collect($articleComments)->merge(collect($topicComments))->sortByDesc('created_time')->values()->all();

        return $this->success('success', $list);
    }

    public function getPhone(Request $request)
    {
        $code = $request->input('code');
        if (!$code) {
            return $this->error('code不能为空');
        }

        try {
            $settings = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP);
//            $miniProgram = \EasyWeChat::miniProgram();
            $miniProgram = Factory::miniProgram(array_merge([
                'app_id' => $settings[MiniProgramConstant::APP_ID],
                'secret' => $settings[MiniProgramConstant::APP_SECRET],
            ], config('wechat.defaults')));
            $data = $miniProgram->phone_number->getUserPhoneNumber($code);
        } catch (\Exception $e) {
            log_exception('微信获取手机号异常', $e);
            return $this->error('未获取到手机号');
        }

        $phone = $data['phone_info']['purePhoneNumber'] ?? $data['phone_info']['phoneNumber'] ?? '';
        if (!$phone) {
            return $this->error('未获取到手机号');
        }

        return $this->_success(compact('phone'));
    }

    public function bindPhone(Request $request)
    {
        $data = Validator::make($request->post(), [
            'phone' => 'required',
            'code'  => 'required',
        ], [
            'phone.required' => '手机号不能为空',
            'code.required'  => '验证码不能为空',
        ])->validate();

        if (!SmsService::instance()->check($data['phone'], $data['code'])) {
            return $this->error('验证码错误');
        }

        $exists = Member::query()
            ->where('phone', '=', $data['phone'])
            ->where('mini_type', '=', $this->getMiniType())
            ->exists();
        if ($exists) {
            return $this->error('手机号已被绑定');
        }

        Member::query()
            ->where('id', '=', auth('api')->user()->id)
            ->update(['phone' => $data['phone']]);

        return $this->success('绑定成功');
    }

    public function vipEquity()
    {
        $memberId = auth('api')->user()->id;

        $member = Member::find($memberId);
        if (!$member) return $this->error('账号不存在');
        if (!$member->is_vip) return $this->error('当前不是vip');

        $member->update(['vip_show_adv' => $member->vip_show_adv ? 0 : 1]);

        return $this->success('操作成功');
    }
}
